package com.test.controller;

import com.test.entity.Const;
import com.test.entity.RestBean;
import com.test.service.ImageService;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@RestController
@Slf4j
@RequestMapping("/api/image")
public class ImageController {
    @Resource
    ImageService imageService;
    @PostMapping("/cache")
    public RestBean<String> uploadImage(@RequestParam("file") MultipartFile file,
                                        @RequestAttribute(Const.VERIFY_USER_ID) int id,
                                        HttpServletResponse response) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        if(file.getSize()>1024*5*1024){
            return RestBean.failure(400,"上传文件不得大于5M");
        }
        log.info("正在进行图片上传");
        String url = imageService.uploadImage(file, id);
        log.info("图片上传成功");
        if (url != null){
            log.info("图片上传成功,大小是："+file.getSize());
            return RestBean.success(url);
        }
        log.info("图片上传失败,上传次数过多");
        response.setStatus(400);
        return RestBean.failure(400,"图片上传失败");


    }
    @PostMapping("/avatar")
    public RestBean<String> uploadAvatar(@RequestParam("file") MultipartFile file,
                                         @RequestAttribute(Const.VERIFY_USER_ID) int id) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        if(file.getSize() >1024*100){
            return RestBean.failure(400,"上传文件不得大于100kb");
        }
        log.info("正在进行头像上传");
        String url = imageService.uploadAvatar(file, id);
        log.info("头像上传成功");
        if (url != null){
            log.info("头像上传成功,大小是："+file.getSize());
            return RestBean.success(url);

        }
        return RestBean.failure(400,"头像上传失败");



    }
    
}
